﻿Imports CoreAudioApi
Imports System.Threading

Public Class ucEAC
    Private DevEnum As New MMDeviceEnumerator()
    Private device As MMDevice
    Private session As AudioSessionControl
    Private ProcInt As Integer = 0
    Private meterInformation As AudioMeterInformation
    Private t As Thread


    Private Sub ucEAC_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        t = New Thread(AddressOf EACInit)
        t.Start()
    End Sub

    Public Sub EACInit()
        While Not ProcInt = Process.GetCurrentProcess().Id
            device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia)
            Dim i As Integer = 0
            Do While i < device.AudioSessionManager.Sessions.Count
                'Debug.Print(Process.GetCurrentProcess().Id & " " & device.AudioSessionManager.Sessions(i).ProcessID)
                If device.AudioSessionManager.Sessions(i).ProcessID = Process.GetCurrentProcess().Id Then
                    session = device.AudioSessionManager.Sessions(i)
                    ProcInt = device.AudioSessionManager.Sessions(i).ProcessID
                End If
                i = i + 1
            Loop
        End While
    End Sub

    Public Sub EACTick()
        'Debug.Print("Tic")
        If ProcInt = Process.GetCurrentProcess().Id Then
            'device = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia)
            If session.State = AudioSessionState.AudioSessionStateActive Then
                'Debug.Print(LeftPeak)
                pkLeft.Value = LeftPeak()
                pkRight.Value = RightPeak()
            End If
        End If
        'Debug.Print("Toc")
    End Sub

    Public Function LeftPeak() As Integer
        Dim Input As Integer = session.AudioMeterInformation.PeakValues(0) * 100
        If Input >= 100 Then
            Input = 100
        End If
        Return Input
    End Function

    Public Function RightPeak() As Integer
        Dim Input As Integer = session.AudioMeterInformation.PeakValues(1) * 100
        If Input >= 100 Then
            Input = 100
        End If
        Return Input
    End Function

    Private Sub ucEAC_Resize(sender As Object, e As EventArgs) Handles MyBase.Resize
        pkLeft.Width = ((Me.ClientSize.Width / 2))
        pkRight.Width = ((Me.ClientSize.Width / 2))
    End Sub

    Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles Timer1.Tick
        EACTick()
    End Sub

    Public Sub [Exit]()
        If t.IsAlive = True Then
            t.Abort()
        End If
    End Sub
End Class
